package net.pm.misc;

import java.util.LinkedHashSet;

import javax.annotation.Resource;

import net.pm.core.cache.CityCache;
import net.pm.core.cache.DistrictCache;
import net.pm.core.cache.PMPowerCache;
import net.pm.core.cache.ProvinceCache;
import net.pm.core.entities.db.City;
import net.pm.core.entities.db.District;
import net.pm.core.entities.db.Pmpower;
import net.pm.core.entities.db.Province;
import net.pm.core.service.addr.CityServicer;
import net.pm.core.service.addr.DistrictServicer;
import net.pm.core.service.addr.ProvinceServier;
import net.pm.core.service.power.PMPowerServicer;

import org.apache.log4j.Logger;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

/**
 * 启动后的一些操作
 */
@Component("StartupHelper")
public final class StartupHelper implements
		ApplicationListener<ContextRefreshedEvent> {
	Logger logger = Logger.getLogger(StartupHelper.class);

	private static Boolean listenned = false;
	@Resource(name = "ProvinceServier")
	private ProvinceServier provinceServier;
	@Resource(name = "CityServicer")
	private CityServicer cityServicer;
	@Resource(name = "DistrictServicer")
	private DistrictServicer districtServicer;
	@Resource(name = "PMPowerServicer")
	private PMPowerServicer powerServicer;

	// 当ApplicationContext初始化或者刷新时触发该事件
	@Override
	public void onApplicationEvent(ContextRefreshedEvent event) {
		// 启动时,,会调用两次
		if (listenned)
			return;

		logger.info("Spring启动后执行的操作...");
		execute();
		logger.info("Spring启动后执行的操作,结束...");
		
		listenned = true;
	}

	private void execute() {

		// 绑定省市区缓存
		initAddressCache();
		// 绑定权限缓存
		initPmpowerCache();
	}

	/**
	 * 权限
	 */
	private void initPmpowerCache() {
		// 所有权限的缓存
		PMPowerCache.setPmpowerset(new LinkedHashSet<Pmpower>(powerServicer
				.findAll()));
	}

	/**
	 * 绑定省市区缓存
	 */
	private void initAddressCache() {
		// 省份
		ProvinceCache.setProvinceSet(new LinkedHashSet<Province>(
				provinceServier.findAll()));
		// 城市
		CityCache.setCitySet(new LinkedHashSet<City>(cityServicer.findAll()));
		// 区域
		DistrictCache.setDistrictSet(new LinkedHashSet<District>(
				districtServicer.findAll()));
	}

}
